package com.zhaotianhao.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;


public class JDBCUtil {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	public static Connection getConn(){
		try {
			//读取 db.properties
			ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
			if(null == bundle){
				bundle = ResourceBundle.getBundle("db");
			}
			 driver = bundle.getString("jdbc.driver");
			 url = bundle.getString("jdbc.url");
			 username = bundle.getString("jdbc.username");
			 password = bundle.getString("jdbc.password");
			Class.forName(driver);
			return DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void close(AutoCloseable...autoCloseables){
		if(autoCloseables!=null){
			for (AutoCloseable autoCloseable : autoCloseables) {
				if(autoCloseable!=null){
					try {
						autoCloseable.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Connection conn = getConn();
		System.out.println(conn);
	}


	public static int excuteUpdate(String sql, Object[] params,Connection conn) {
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			//给占位符赋值
			//判断params是否为空
			if(params!=null){
				for (int i = 0; i < params.length; i++) {
					//？占位符从1开始
					ps.setObject(i+1, params[i]);
				}
			}
			//执行增、删除、改
			int count = ps.executeUpdate();
			return count;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
}
